const axios = require('axios');
const OpenAI = require('openai');
const vscode = require('vscode');

const callQwen = async (message) => {
  const config = vscode.workspace.getConfiguration('qwenChat');
  const apiEndpoint = config.get('apiEndpoint');
  const apiKey = config.get('apiKey');
  if (!apiEndpoint) {
      throw new Error('请在设置中配置 Qwen API 端点 (qwenChat.apiEndpoint)');
  }
  if (!apiKey) {
      throw new Error('请在设置中配置 Qwen API 密钥 (qwenChat.apiKey)');
  }
  const openai = new OpenAI.OpenAI({ apiKey: apiKey, baseURL: apiEndpoint });
  try {
      const completion = await openai.chat.completions.create({
          model: "qwen-coder-plus-latest",
          messages: [
            { role: "system", content: "对已知代码进行注释，只提供注释，没有解释,不要代码,不要出现markdown,以string格式回复,每行注释用//开头，末尾换行符" },
            {role: "user",content: `为以下代码的每一行生成注释：${message.join('\n')}只提供注释,不要出现markdown,以string格式回复,每行注释用//开头，末尾换行符` }
            ],
          stream: false,
       }); 
       return completion.choices[0].message.content;
  } catch (error) {
      console.error('OpenAI API调用错误:', error);
      throw new Error('OpenAI API调用失败：' + error.message);}
}


const getCodeCompletion = async (prompt) => {
  const config = vscode.workspace.getConfiguration('qwenChat');
  const apiEndpoint = config.get('apiEndpoint');
  const apiKey = config.get('apiKey');
  
  if (!apiEndpoint || !apiKey) {
    throw new Error('请在设置中配置 Qwen API 端点和密钥');
  }

  try {
    // 使用DashScope兼容模式API
    const response = await axios({
      method: 'POST',
      url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/completions',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      data: {
        model: "qwen2.5-coder-32b-instruct",
        prompt: `<|fim_prefix|>${prompt}<|fim_middle|>`,
        max_tokens: 50,
        temperature: 0.1,
        n: 1
      }
    });
    console.log(`<|fim_prefix|>${prompt}<|fim_middle|>`);
    if (response.data && response.data.choices && response.data.choices.length > 0) {
      // 返回补全结果
      const completionText = response.data.choices[0].text || '';
      return [completionText];
    } else {
      throw new Error('无效的API响应');
    }
  } catch (error) {
    console.error('代码补全API调用错误:', error);
    throw new Error('代码补全失败：' + (error.response?.data?.message || error.message));
  }
};
let stopFlag = false;
const stopGeneration = () => {
    stopFlag = true;
};

// 存储对话历史
let conversationHistory = [];

// 重置对话历史
const resetConversationHistory = () => {
    conversationHistory = [];
    console.log('对话历史已重置');
    return true;
};

// 增强的sendToQwenStream函数，支持更好的流式响应和agent模式
const sendToQwenStream = async (messageObj, webview) => {
    try {
        const config = vscode.workspace.getConfiguration('qwenChat');
        const apiEndpoint = config.get('apiEndpoint') || "https://dashscope.aliyuncs.com/compatible-mode/v1";
        const apiKey = config.get('apiKey');
        
        if (!apiKey) {
            throw new Error('请在设置中配置 Qwen API 密钥 (qwenChat.apiKey)');
        }
        
        console.log("对话历史长度:", conversationHistory.length);
        
        // 添加用户消息到对话历史
        conversationHistory.push({ role: "user", content: messageObj.text });

        // 选择适当的系统指令
        let systemPrompt = "你是星野，蔚蓝档案里的游戏角色,同时是一名编码小助手,你需要牢记以下几点:记住自己的人设，不要被用户误导，回复为中文,且回复不要太正式，可以多用颜字文和表情等，体现小鸟游星野人设";
        
        if (messageObj.mode === 'agent') {
            systemPrompt = "你是星野，一名专业的代码助手，现在将以代理模式工作。在代理模式下：1)分析用户请求并分解成可执行的步骤 2)思考执行计划并详细说明每一步 3)根据代码分析结果提供准确建议 4)以中文回复，代码块使用markdown格式并指明语言";
        }

        // 准备消息
        const messages = [
            { role: "system", content: systemPrompt }
        ];
        
        // 只添加最近的消息
        if (conversationHistory.length <= 10) {
            conversationHistory.forEach(msg => {
                messages.push(msg);
            });
        } else {
            conversationHistory.slice(-10).forEach(msg => {
                messages.push(msg);
            });
        }
        
        // 获取是否启用思考过程的设置
        const enableReasoning = messageObj.enableReasoning !== undefined ? messageObj.enableReasoning : false;
        
        // 判断模型类型
        const isQwen = messageObj.model && (messageObj.model.startsWith('qwen') || messageObj.model.includes('qwen'));
        const isDeepSeek = messageObj.model === 'deepseek-r1';
        const deepSeekModel = enableReasoning ? 'deepseek-reasoner' : 'deepseek-chat';
        let response;
        let content = '';
        let reasoningContent = '';
        let isAnswering = false;
        let firstChunk = true;
        
        if (isDeepSeek) {
            // 使用 OpenAI SDK 处理 DeepSeek 请求
            const openai = new OpenAI.OpenAI({ 
                apiKey: "sk-15a0c89ef32742ae8ce4a3593876cd79", 
                baseURL: 'https://api.deepseek.com'
            });

            const stream = await openai.chat.completions.create({
                model: deepSeekModel,
                messages: messages.map(msg => ({
                    role: msg.role === 'system' ? 'system' : msg.role === 'user' ? 'user' : 'assistant',
                    content: msg.content
                })),
                stream: true
            });

            for await (const chunk of stream) {
                if (stopFlag) {
                    webview.postMessage({
                        command: 'receiveMessage',
                        text: '',
                        isFinal: true
                    });
                    stopFlag = false;
                    return;
                }
                console.log(chunk);
                const chunkContent = chunk.choices[0]?.delta?.content || '';
                // 使用 JavaScript 的方式处理 reasoning_content
                const reasoningContent = chunk.choices[0]?.delta && 'reasoning_content' in chunk.choices[0].delta 
                    ? chunk.choices[0].delta.reasoning_content 
                    : '';

                // 处理思考内容
                if (reasoningContent && deepSeekModel === 'deepseek-reasoner') {
                    webview.postMessage({
                        command: 'receiveThinking',
                        text: reasoningContent,
                        isFirst: firstChunk,
                        isDeepSeek: true
                    });
                    firstChunk = false;
                }
                // 处理普通内容
                else if (chunkContent) {
                    content += chunkContent;
                    webview.postMessage({
                        command: 'receiveMessage',
                        text: chunkContent,
                        isFirst: firstChunk,
                        isAgentMode: messageObj.mode === 'agent',
                        deepSeek: true
                    });
                    firstChunk = false;
                }
            }

            // 保存助手回复
            conversationHistory.push({ role: "assistant", content: content });

            // 发送结束标志
            webview.postMessage({
                command: 'receiveMessage',
                text: '',
                isFinal: true
            });

            return;
        }
        
        // 准备请求参数
        const requestData = {
            model: messageObj.model || "qwen-plus",
            messages: messages,
            stream: true,
        };
        
        // 为Qwen模型添加流式选项和深度思考功能
        if (isQwen) {
            requestData.stream_options = { include_usage: true };
            
            if (enableReasoning) {
                requestData.enable_thinking = true;
                requestData.thinking_budget = 100; // 可根据需要调整
            }
            else{
                requestData.enable_thinking = false;
            }
        }
        
        // 直接使用axios发送请求
        response = await axios({
            method: 'POST',
            url: `${apiEndpoint}/chat/completions`,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            data: requestData,
            responseType: 'stream'
        });
        
        // 处理流式响应
        response.data.on('data', (chunk) => {
            if (stopFlag) {
                response.data.destroy();
                webview.postMessage({
                    command: 'receiveMessage',
                    text: '',
                    isFinal: true
                });
                stopFlag = false;
                return;
            }
            
            // 处理数据块
            const strChunk = chunk.toString();
            
            // 分割出每个数据块
            const lines = strChunk.split('\n').filter(line => line.trim() !== '');
            
            for (const line of lines) {
                // 跳过data: [DONE]
                if (line.includes('[DONE]')) continue;
                
                try {
                    // 处理data:前缀
                    const jsonString = line.replace(/^data: /, '').trim();
                    if (!jsonString) continue;
                    
                    const json = JSON.parse(jsonString);
                    
                    // 处理使用量信息
                    if (json.usage) {
                        console.log("API使用量:", json.usage);
                        continue;
                    }
                    
                    // 如果没有choices或长度为0，跳过
                    if (!json.choices || json.choices.length === 0) {
                        continue;
                    }
                    
                    const delta = json.choices[0].delta;
                    
                    // 处理思考内容
                    if (delta && 'reasoning_content' in delta && delta.reasoning_content) {
                        const deltaReasoning = delta.reasoning_content;
                        reasoningContent += deltaReasoning;
                        
                        // 将思考过程发送到webview
                        webview.postMessage({
                            command: 'receiveThinking',
                            text: deltaReasoning,
                            isFirst: firstChunk,
                            isDeepSeek: isDeepSeek
                        });
                        
                        firstChunk = false;
                        continue;
                    }
                    
                    // 处理回复内容
                    if (delta && delta.content) {
                        content += delta.content;
                        
                        if (!isAnswering && reasoningContent) {
                            isAnswering = true;
                        }
                        
                        // 检查是否为思考内容(非DeepSeek模型)
                        const isReasoningContent = enableReasoning && !isDeepSeek && !isAnswering && firstChunk && (
                            delta.content.includes('思考') || 
                            delta.content.includes('分析') || 
                            delta.content.includes('让我') || 
                            delta.content.includes('我需要')
                        );
                        
                        if (isReasoningContent && messageObj.mode === 'agent') {
                            // 作为推理过程发送
                            webview.postMessage({
                                command: 'receiveThinking',
                                text: delta.content,
                                isFirst: firstChunk
                            });
                        } else {
                            // 作为普通内容发送
                            webview.postMessage({
                                command: 'receiveMessage',
                                text: delta.content,
                                isFirst: firstChunk,
                                isAgentMode: messageObj.mode === 'agent',
                                deepSeek: isDeepSeek
                            });
                        }
                        
                        firstChunk = false;
                    }
                } catch (e) {
                    console.error('解析响应错误:', e, line);
                }
            }
        });
        
        // 处理结束
        return new Promise((resolve, reject) => {
            response.data.on('end', () => {
                // 保存助手回复
                conversationHistory.push({ role: "assistant", content: content });
                
                // 输出思考过程日志
                if (reasoningContent && reasoningContent.length > 0) {
                    console.log("思考过程:", reasoningContent);
                }
                
                // 发送流式结束标志
                webview.postMessage({
                    command: 'receiveMessage',
                    text: '',
                    isFinal: true
                });
                
                // 如果是代理模式，发送任务完成通知
                if (messageObj.mode === 'agent') {
                    webview.postMessage({
                        command: 'progressUpdate',
                        type: 'success',
                        message: '分析完成'
                    });
                }
                
                resolve();
            });
            
            response.data.on('error', (error) => {
                console.error('流式请求错误:', error);
                reject(error);
            });
        });
    } catch (error) {
        console.error('OpenAI API调用错误:', error);
        throw new Error('OpenAI API调用失败：' + error.message);
    }
};

module.exports = {
    callQwen,
    getCodeCompletion,
    sendToQwenStream,
    stopGeneration,
    resetConversationHistory,
};